/**
 * Model implementation
 */

#include "Model.h"

/////////////////////////////////////////////////

void Model::translate(const Vec3& v)
{
	std::vector<PartPtr>::iterator iter;
	std::vector<Vec3>::iterator vIter;
	for (iter=parts.begin(); iter!=parts.end(); ++iter) {
		for (vIter=(*iter)->verts.begin(); vIter!=(*iter)->verts.end(); ++vIter) {
			(*vIter) += v;
		}
	}
}

/////////////////////////////////////////////////

void Model::scale(const float s)
{
	std::vector<PartPtr>::iterator iter;
	std::vector<Vec3>::iterator vIter;
	for (iter=parts.begin(); iter!=parts.end(); ++iter) {
		for (vIter=(*iter)->verts.begin(); vIter!=(*iter)->verts.end(); ++vIter) {
			(*vIter) *= s;
		}
	}
}

/////////////////////////////////////////////////

void Model::skipLine(std::istream& is)
{
    char next;
    is >> std::noskipws;
    while( (is >> next) && ('\n' != next) );
}


/////////////////////////////////////////////////

void Model::loadOBJ(const std::string& objfile)
{
    PartPtr part(new Part());
    std::string token;
    float x, y, z;
    int fv[3];
    //int ft[3];
    int fn[3];
    char next;
    Vec3 vec;


    std::ifstream obj;
    obj.open(objfile.c_str());
    
    if (!obj.good())
    {
        std::cout << "bad objfile" << std::endl;
        return;
    }
    while( !obj.eof() )
    {
        while( obj >> std::skipws >> next )
        {
            obj.putback(next);
            if ('#' == next)
                skipLine(obj);
            else
                break;
        }

        obj >> token;

        if (token == "g")
        {
            skipLine(obj);
        }
        else if (token == "v")
        {
            obj >> x >> y >> z;
            part->verts.push_back(Vec3( x, y, z));
        }
        else if (token == "vn")
        {
            obj >> x >> y >> z;
            part->norms.push_back(Vec3( x, y, z));
        }
        else if (token == "vt")
        {
            skipLine(obj);
        }
        else if (token == "mtllib")
        {
            skipLine(obj);
        }
        else if (token == "usemtl")
        {
            skipLine(obj);
        }
        else if (token == "f")
        {
            char c;
            for (int i=0; i<3; i++)
            {
                obj >> fv[i];
                c = obj.get();
                c = obj.get();
                //obj.ignore(1, '/');
                //obj >> ft[i];
                //obj.ignore(1, '/');
                obj >> fn[i];
            }
            part->tris.push_back(Triangle( fv[0]-1, fv[1]-1, fv[2]-1, fn[0]-1, fn[1]-1, fn[2]-1 ));

        }

    }
    std::cout << objfile << std::endl;
    std::cout << "  Verts: " << part->verts.size() << std::endl;
    std::cout << "  Norms: " << part->norms.size() << std::endl;
    std::cout << "  Tris: " << part->tris.size() << std::endl;

    parts.push_back(part);

}





        
        
        


